
import axios from "axios"
import {baseURL} from "./config"
import {Toast,Notify } from "vant"
import router from '@/router'
console.log(baseURL);
const AUTH_TOKEN = "";

// axios.defaults.baseURL = baseURL;    // 服务接口的基记录 
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout =  60000;


// axios.create({
//     baseURL,
//     timeout: 60000,
//     headers: {}
// });




export function ShowLoading(){
    Toast.clear()
    Toast.loading({
        message: '请求中...',
        forbidClick: true,
    });
}

export function ShowSuccess(msg){
    Toast.clear()
    msg = msg || '请求成功'
    Notify({ type: 'success', message: msg});
}

export function ShowFail(msg){
    Toast.clear()
    msg = msg || '请求失败'
    Notify({
        message:msg,
        color: '#ad0000',
        background: '#ffe1e1',
    });
      
}



// 拦截器Interceptors

// 请求发送之前 
axios.interceptors.request.use(function (config) {
    const server_token = localStorage.getItem("server_token")
    // console.log(server_token)
    config.headers.common['_token'] = server_token;
    // console.log(config)   // 请求的参数信息  包括 body  params query 
    
    ShowLoading();
    return config;
}, function (error) {
    ShowFail("请求失败")
    return Promise.reject(error);
});

// 请求响应完成 
axios.interceptors.response.use(function (response) {
    
    Toast.clear()
    // 响应成功  
    console.log(response.data)
    if(response.data.code==200){
        // 成功
        // ShowSuccess(response.data.msg)
    }else if(response.data.code==402 || response.data.code==404 || response.data.code==500 || response.data.code==503 ){
        ShowFail(response.data.msg)
    }else if(response.data.code==3000){
        ShowFail(response.data.msg)
        router.replace({name:'login'})
    }

    return response;
}, function (error) {
    ShowFail("响应失败")
    return Promise.reject(error);
});

// get 请求 
export const get = function(url,params,headers){
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params,
            headers
        })
        .then(res=>{
            resolve(res.data)  // data 消除
        })
        .catch(err=>{
            reject(err)
        })
    })
}

// POST  请求 
export const post = function(url,body,headers,params){
    return new Promise(function(resolve,reject){
        axios.post(url,body,{
            params,
            headers
        })
        .then(res=>{
            resolve(res.data)  // data 消除
        })
        .catch(err=>{
            reject(err)
        })
    })
}